package com.xyht.sca_s.student_manage_system.common.desEncodeAndDecode;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

@Slf4j
@Component
public class DesCbcUtil {
    // 加解密统一使用的编码方式
    private String encoding = "UTF-8";
    @Value("${config.encode_scan_switch}")
    private boolean encode_scan_switch;

    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     * @return 加密后的文本，失败返回null
     */
    public String encode(String plainText, String secretKey, String iv) {
        String result = null;
        try {
            DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
            Key desKey = secretKeyFactory.generateSecret(deSedeKeySpec);
//            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            Cipher cipher = Cipher.getInstance("desede/ECB/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
//            cipher.init(Cipher.ENCRYPT_MODE, desKey, ips);
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
            result = Base64Utils.encodeToString(encryptData);
        } catch (Exception e) {
            log.error("DesCbcUtil encode error : {}", e);
        }
        return result;
    }

    public <T> T encryptDES(String encryptString, String encryptKey){
//        if (!SCAN_ANNOTATION){
//            return (T) encryptString;
//        }
//        if (!encode_scan_switch){
//            Object object = JSONObject.parseObject(encryptString,Object.class);
//            return  (T) encryptString;
//        }
        byte[] encryptedData = new byte[0];
        try{
            SecretKeySpec key = new SecretKeySpec(getKey(encryptKey), "DES");
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encryptedData = cipher.doFinal(encryptString.getBytes());
//        return bytesToHexString(encryptedData);
        }catch (Exception e){
            e.printStackTrace();
        }
        return  (T) Base64Utils.encodeToString(encryptedData);
    }

    public final String bytesToHexString(byte[] bArray) {
        if(bArray == null )
        {
            return "";
        }
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }



    public byte[] getKey(String keyRule) {
        Key key = null;
        byte[] keyByte = keyRule.getBytes();
        // 创建一个空的八位数组,默认情况下为0
        byte[] byteTemp = new byte[8];
        // 将用户指定的规则转换成八位数组
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
            byteTemp[i] = keyByte[i];
        }
        key = new SecretKeySpec(byteTemp, "DES");
        return key.getEncoded();
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return 解密后明文，失败返回null
     */
    public String decode(String encryptText, String secretKey, String iv) {
        String result = null;
        try {
//            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
//            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
//            Key desKey = secretKeyFactory.generateSecret(spec);
            log.debug("开始解密++++++++++++++");
            SecretKeySpec key = new SecretKeySpec(getKey(secretKey), "DES");
//            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decryptData = cipher.doFinal(Base64Utils.decodeFromString(encryptText));
            result = new String(decryptData, encoding);
        } catch (Exception e) {
            log.error("DesCbcUtil decode error : {}", e.getMessage());
        }
        return result;
    }

}
